﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using FieldDevice;
using FieldDevice.ModBus;
using FieldDevice.Emulation;


namespace FieldDevice.UI
{
    public partial class DeviceForm : DeviceFormBase
    {

        public DeviceForm(Device device)
            :base(device)
           
        {
            InitializeComponent();
            this.ReadChangeEventHander =
            new Device.ReadChangeEventHander(device_ReadChangeEvent);
            device.ReadChangeEvent += this.ReadChangeEventHander;
            UpdateReadsDelegate = new VoidDelegate(this.UpdateReads);
        }
        CurveMapForm curveMapForm;
        CurrentBarForm currentbar;
        void device_ReadChangeEvent(Device device, string name, float value)
        {
            if (this.InvokeRequired)
                this.Invoke(this.UpdateReadsDelegate);
            else
                this.UpdateReads();
        }
        public bool ReadEnergy = false;
        private float V_Ratio = 1;              //电压的系数
        private string P_Unit="W";              //有功功率功率单位
        private string Q_Unit="var";            //无功功率单位
        private string S_Unit="VAR";            //视在功率单位
        private string I_Unit="A";              //电流单位
        private string V_Unit="V";              //电压单位

        public string ShowUA
        {
            get { return VolA.Text;}
            set
            {
                VolA.Text = value;
                this.Refresh();
            }
        }

        public string ShowUB
        {
            get
            {
                return VolB.Text;
            }
            set
            {
                VolB.Text = value;
                this.Refresh();
            }
        }
        public string ShowUC
        {
            get { return VolC.Text; }
            set
            {
                VolC.Text = value;
                this.Refresh();
            }
        }

        public string Ia
        {
            get { return CurA.Text; }
            set {
                CurA.Text = value;
                this.Refresh();
            }
        
        }

        public string Ib
        {
            get { return CurB.Text; }
            set
            {
                CurB.Text = value;
                this.Refresh();
            }

        }

        public string Ic
        {
            get { return CurC.Text; }
            set
            {
                CurC.Text = value;
                this.Refresh();
            }

        }

        public string P
        {
            get { return P_Value.Text; }
            set {
                P_Value.Text = value;
                this.Refresh();
            }
        }


        public string Q
        {
            get { return Q_Value.Text; }
            set
            {
                Q_Value.Text = value;
                this.Refresh();
            }
        }


        public string S
        {
            get { return S_Value.Text; }
            set
            {
                S_Value.Text = value;
                this.Refresh();
            }
        }
        void Form1_ReadChangeEvent(string name, float value)
        {
            throw new NotImplementedException();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            this.UpdateReads();
            if (ReadEnergy == true)
            {
                AddEnergyList();
            }
        }

        public override void UpdateReads()
        {
            bool success = true;
            try
            {
                SwitchingValues();                          //读取开关量状态
                DigitalDisplay();
                ListFunction();
                if (curveMapForm != null)
                {
                    curveMapForm.UpdateReads();
                }
                switch (Device1.Category)
                {
                    case Device.DeviceCategory.PowerMeter:
                        this.button_CurBar.Visible = true;
                        if (this.currentbar != null)
                            Cur_Bar();//电流窗口打开
                        break;
                    default:
                        break;
                }
            }
            
            catch (Exception exp)
            {
                success = false;
                this.labelCommAlarm.Text = "通信异常:" + exp.ToString();
            }

            if (success == true)
            {
                this.SwitchAlarm(false);
                this.labelCommAlarm.BackColor = Color.Green;
                this.labelCommAlarm.Text = "通信正常";
            }
            else
                this.SwitchAlarm(true);
        }

        void SwitchAlarm(bool on)
        {
            if (on)
            {
                this.panel1.BackColor = Color.Red;
            }
            else
                this.panel1.BackColor = Color.Green;
        }

        private void buttonUpdateReads_Click(object sender, EventArgs e)
        {
            try
            {
                this.Device1.DebugReads();
                this.UpdateReads();
            }
            catch (Exception exp)
            {
                this.labelCommAlarm.BackColor = Color.Red;
                this.labelCommAlarm.Text = "通信异常:" + exp.ToString();
            }
        }

        public void SwitchingValues()
        { 
           switch(Device1.Category)
           {
            case Device.DeviceCategory.PowerMeter:
                    //判断第一路输入量是开闸还是合闸
                    if (this.Device1.OnOff)
                    {
                        PictureBox_DI1.Image = global::FieldDevice.Properties.Resources.合闸;
                        this.YX_Box.Text ="合闸";
                        this.YX_Box.ForeColor = Color.Green;
                    }
                    else
                    {
                        PictureBox_DI1.Image = global::FieldDevice.Properties.Resources.开闸;
                        this.YX_Box.Text ="开闸";
                        this.YX_Box.ForeColor = Color.Red;               
                    }
               break;
               case Device.DeviceCategory.HighVoltageDevice:
                   if (this.Device1.CurrentReads["OperationCondition_Work"] == 1)
                   {
                       PictureBox_DI1.Image = global::FieldDevice.Properties.Resources.合闸;
                       this.YX_Box.Text = "合闸";
                       this.YX_Box.ForeColor = Color.Green;
                   }
                   if (this.Device1.CurrentReads["OperationCondition_Stop"] == 1)
                   {
                       PictureBox_DI1.Image = global::FieldDevice.Properties.Resources.开闸;
                       this.YX_Box.Text = "开闸";
                       this.YX_Box.ForeColor = Color.Red;
                   }
                   break;
               case Device.DeviceCategory.EmaxE3:
                   if (this.Device1.CurrentReads["CB_Connected"] == 1)
                   {
                       PictureBox_DI1.Image = global::FieldDevice.Properties.Resources.合闸;
                       this.YX_Box.Text = "合闸";
                       this.YX_Box.ForeColor = Color.Green;
                   }
                   else
                   {
                       PictureBox_DI1.Image = global::FieldDevice.Properties.Resources.开闸;
                       this.YX_Box.Text = "开闸";
                       this.YX_Box.ForeColor = Color.Red;
                   }
                   break;
               default:
                break;
            }
        }
        private void DeviceForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (this.Device1 != null)
                this.Device1.ReadChangeEvent -= this.device_ReadChangeEvent;
        }

        public void DigitalDisplay()
        {
           
            string devicetypename = Device1.GetType().Name;
            switch (this.Device1.Category)
            { 
                case Device.DeviceCategory.HighVoltageDevice:
                    V_Unit = "KV";
                    I_Unit = "A";
                    ShowUA = (Device1.CurrentReads["VA"] / 1000).ToString("F2") + V_Unit;
                    ShowUB = (Device1.CurrentReads["VB"] / 1000).ToString("F2") + V_Unit;
                    ShowUC = (Device1.CurrentReads["VC"] / 1000).ToString("F2") + V_Unit;
                    break;
                default:
                    ShowUA = Device1.CurrentReads["VA"].ToString("F2") + V_Unit;
                    ShowUB = Device1.CurrentReads["VB"].ToString("F2") + V_Unit;
                    ShowUC = Device1.CurrentReads["VC"].ToString("F2") + V_Unit;
                    break;
            }

            Ia = Device1.CurrentReads["IA"].ToString("F2") + I_Unit;
            Ib = Device1.CurrentReads["IB"].ToString("F2") + I_Unit;
            Ic = Device1.CurrentReads["IC"].ToString("F2") + I_Unit;

            ///
            /// 读取有功电度的值
            ///
            if (Device1.CurrentReads["P"] > 1000 && Device1.CurrentReads["P"]<1000000)
            {
                P_Unit = "KW";
                P = (Device1.CurrentReads["P"] / 1000.0f).ToString("F2") + P_Unit;
            }
            else
                if (Device1.CurrentReads["P"] > 1000000)
                {
                    P_Unit = "MW";
                    P = (Device1.CurrentReads["P"] / 1000000.0f).ToString("F2") + P_Unit;
                }
                else
                {
                    P_Unit = "W";
                    P = Device1.CurrentReads["P"].ToString("F2") + P_Unit;
                }
            ///
            /// 读取无功电度的值
            ///
            if (Device1.CurrentReads["Q"] > 1000 && Device1.CurrentReads["Q"]<1000000)
            {
                Q_Unit = "KVar";
                Q = (Device1.CurrentReads["Q"]/1000.0f).ToString("F2") + Q_Unit;
            }
            else
                if (Device1.CurrentReads["Q"] > 1000000)
                {
                    Q_Unit = "MVar";
                    Q = (Device1.CurrentReads["Q"] / 1000000.0f).ToString("F2") + Q_Unit;
                }
                else
                {
                    Q_Unit = "Var";
                    Q = Device1.CurrentReads["Q"].ToString("F2") + Q_Unit;
                }
                
            ///
            /// 读取视在功率的值
            ///
            if (Device1.CurrentReads["S"] > 1000 && Device1.CurrentReads["S"]<1000000)
            {
                S_Unit = "KVAR";
                S = (Device1.CurrentReads["S"]/1000.0f).ToString("F2") + S_Unit;
            }
            else
                if (Device1.CurrentReads["S"] > 1000000)
                {
                    S_Unit = "MVAR";
                    S = (Device1.CurrentReads["S"] / 1000000.0f).ToString("F2") + S_Unit;
                }
                else
                {
                    S_Unit = "VAR";
                    S = Device1.CurrentReads["S"].ToString("F2") + S_Unit;
                }
        }

        public void ListFunction()
        {
            ListDisplay.Items.Clear();
            ListOrderCount = 1;
            if (Device1.CurrentReads["Vab"] / V_Ratio > 1000)
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Vab", "AB线电压", (Device1.CurrentReads["Vab"] / (V_Ratio * 1000.0f)).ToString("F2") + V_Unit));
            }
            else
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Vab", "AB线电压", (Device1.CurrentReads["Vab"] / (V_Ratio)).ToString("F2") + V_Unit));
            }
            if (Device1.CurrentReads["Vbc"] / V_Ratio > 1000)
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Vbc", "BC线电压", (Device1.CurrentReads["Vbc"] / (V_Ratio * 1000.0f)).ToString("F2") + V_Unit));
            }
            else
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Vbc", "BC线电压", (Device1.CurrentReads["Vbc"] / (V_Ratio)).ToString("F2") + V_Unit));
            }
            if (Device1.CurrentReads["Vbc"] / V_Ratio > 1000)
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Vca", "CA线电压", (Device1.CurrentReads["Vca"] / (V_Ratio*1000.0f)).ToString("F2") + V_Unit));
            }
            else
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Vca", "CA线电压", (Device1.CurrentReads["Vca"] / V_Ratio).ToString("F2") + V_Unit));
            }
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "VA", "A相电压", ShowUA));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "VB", "B相电压", ShowUB ));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "VC", "C相电压", ShowUC));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "IA", "A相电流", Ia));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "IB", "B相电流", Ib));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "VC", "C相电流", Ic));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "P", "有功功率", P));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "Q", "无功功率", Q));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "S", "视在功率", S));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "PF", "功率因数", Device1.CurrentReads["PF"].ToString("F2")));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "FR", "频率", Device1.CurrentReads["FR"].ToString("F2")));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "EPI", "有功电度", Device1.CurrentReads["EPI"].ToString("F2") + " Kwh"));
            ListDisplay.Items.Add(ListDetail(ListOrderCount, "EQL", "无功电度", Device1.CurrentReads["EQL"].ToString("F2") + " Kvarh"));
            ListDisplay.Items.Add(ListDetail(ListOrderCount,"Ratio","比例系数",Device1.CurrentReads["Ratio"].ToString("F2")));
            switch (Device1.Category)
            { 
                case Device.DeviceCategory.PowerMeter:
                    SwitchConditionList();
                    break;
                case Device.DeviceCategory.HighVoltageDevice:
                    HighVoltageConditionList();
                    break;
                case Device.DeviceCategory.EmaxE3:
                    EmaxE3ConditionList();
                    break;
                default:
                    break;
            }
        }
        public void SwitchConditionList()
        {
            if (this.Device1.OnOff)
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "YX", "工作状态", "合闸"));
            }
            else
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "YX", "工作状态", "开闸"));      
        }

        public void HighVoltageConditionList()
        {
            if (this.Device1.CurrentReads["Handcart_Position"] != 0)
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Handcart_Position", "手车位置", "工作"));
            }
            else
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Handcart_Position", "手车位置", "试验"));

            if (this.Device1.CurrentReads["OperationCondition_Work"] == 1)
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Operation Condition", "工作状态", "合闸"));
            if (this.Device1.CurrentReads["OperationCondition_Stop"] == 1)
            {
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Operation Condition", "工作状态", "开闸"));
            }

            if (this.Device1.CurrentReads["Grouding_Switch"] == 1)
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Grouding_Switch", "地刀接地状态", "连接"));
            else
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "Grouding_Switch", "地刀接地状态", "断开"));
        }

        public void EmaxE3ConditionList()
        {
            if (this.Device1.CurrentReads["CB_Connected"] == 1)
                ListDisplay.Items.Add(ListDetail(ListOrderCount, "CB_Connected", "断路器状态", "合闸"));
            else
                ListDisplay.Items.Add(ListDetail(ListOrderCount,"CB_Connected","断路器装他","开闸"));
        }

        private void buttonConfigDevice_Click(object sender, EventArgs e)
        {
            base.ConfigDevice();
        }

        private void Present_DemandButton_Click(object sender, EventArgs e)
        {
            try
            {
                ReadEnergy = true;
                AddEnergyList();
            }
            catch (Exception exp)
            {
                MessageBox.Show(this, exp.ToString());
            }
        }

        private void Clear_Click(object sender, EventArgs e)
        {
            EnergyList.Items.Clear();
            ReadEnergy = false;
        }

        private void HistoryQueryButton_Click(object sender, EventArgs e)
        {
            DateTime time=this.laterTime.Value;                 
        }

        public void AddEnergyList()
        {
            EnergyList.Items.Clear();
            PowerQueue powerValue = new PowerQueue();
            powerValue = Device1.PowerQueues;
            for (int v = 0; v < powerValue.Count; v++)
            {
                ListViewItem list = new ListViewItem((v + 1).ToString());
                list.SubItems.Add(powerValue[v].Time.ToString());
                list.SubItems.Add(powerValue[v].PP.ToString("F2"));
                list.SubItems.Add(powerValue[v].QP.ToString("F2"));
                list.SubItems.Add(powerValue[v].PF.ToString("F2"));
                EnergyList.Items.Add(list);
            }
        }

        private void DeviceForm_Load(object sender, EventArgs e)
        {
            this.deviceHistoryReadsControl1.Device = this.Device1;
            this.UpdateReads();
        }

        private void button_CurBar_Click(object sender, EventArgs e)
        {
            if (currentbar == null)
            {
                currentbar = new CurrentBarForm();
                currentbar.Show();
                currentbar.FormClosed += new FormClosedEventHandler(currentBarForm_FormClosed);
            }
            else
            currentbar.BringToFront();             
        }

        public void Cur_Bar()
        {
            if (Device1.ModbusAddress == 1 && Device1.IPAddress == "192.168.1.101")
            {
                currentbar.currentColumn.Value_1P1[0] = this.Device1.CurrentReads["IA"];
                currentbar.currentColumn.Value_1P1[1] = this.Device1.CurrentReads["IB"];
                currentbar.currentColumn.Value_1P1[2] = this.Device1.CurrentReads["IC"];
            }
            if (Device1.ModbusAddress == 13 && Device1.IPAddress == "192.168.1.101")
            {
                currentbar.currentColumn.Value_1P11[0] = this.Device1.CurrentReads["IA"];
                currentbar.currentColumn.Value_1P11[1] = this.Device1.CurrentReads["IB"];
                currentbar.currentColumn.Value_1P11[2] = this.Device1.CurrentReads["IC"];
            }
            if (Device1.ModbusAddress == 1 && Device1.IPAddress =="192.168.1.103")
            {
                currentbar.currentColumn.Value_2P1[0] = this.Device1.CurrentReads["IA"];
                currentbar.currentColumn.Value_2P1[1] = this.Device1.CurrentReads["IB"];
                currentbar.currentColumn.Value_2P1[2] = this.Device1.CurrentReads["IC"];
            }
        }

        private void curveGraph_Click(object sender, EventArgs e)
        {
            if (curveMapForm == null)
            {
                curveMapForm = new CurveMapForm(this.Device1);
                curveMapForm.Show(this);
                curveMapForm.FormClosed += new FormClosedEventHandler(curveMapForm_FormClosed);
            }
            else
                curveMapForm.BringToFront();
        }

        void curveMapForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.curveMapForm = null;
        }

        void currentBarForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.currentbar = null;
        }

    }

}

